package viewdraw.zjitc.net.androidhomeworkviewdraw;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author 朱志文
 * @data 2019/10/15 0015
 */
public class MyDrawView extends View {
    private Paint paint;
    public MyDrawView(Context context) {
        super(context);
    }

    public MyDrawView(Context context,  AttributeSet attrs) {
        super(context, attrs);
    }

    public MyDrawView(Context context,  AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取资源
        Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dm1);

        Bitmap bitmap = getRoundCornerBitmap(rawBitmap);
        canvas.drawBitmap(bitmap, 0, 0, new Paint());
    }

    public Bitmap getRoundCornerBitmap(Bitmap bitmap) {
       //获取bitmap的宽高
        float bitMapWidth = bitmap.getWidth();
        float bitMapHeight = bitmap.getHeight();
        float viewWidth=getWidth();
        float viewHeight=(viewWidth/bitMapWidth)*bitMapHeight;
       //createBitmao 裁剪图片  Bitmap.Config.ARGB_8888 代表32位ARGB位图
        Bitmap cornerBitmap = Bitmap.createBitmap((int)viewWidth,(int) viewHeight, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas1 = new Canvas(cornerBitmap);
        paint.setAntiAlias(true);
       //在画布上绘制圆形
        canvas1.drawCircle(300,300,100,paint);
       //PorterDuffXfermode(PorterDuff.Mode.SRC_IN) 保持目标像素的源像素，丢弃剩余的源像素和目标像素
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas1.drawBitmap(bitmap, null, new RectF(0, 0, viewWidth, viewHeight), paint);
        return cornerBitmap;
    }

}
